﻿using System;
using System.Linq;
using System.Web.Mvc;
using ARchGL.Declaration.Platform.Service;
using ARchGL.Declaration.Platform.Service.Dtos.Product;
using ARchGL.Declaration.Platform.Web.Models;
using TDF.Web.Attributes.Mvc;

namespace ARchGL.Declaration.Platform.Web.Controllers
{
    public class ProductController : AdminControllerBase
    {
        /// <summary>
        /// 生产服务
        /// </summary>
        protected readonly IProductionService ProductionService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="productionService"></param>
        public ProductController(IProductionService productionService)
        {
            ProductionService = productionService;
        }

        public override ActionResult Index()
        {
            ViewBag.ProductTypeId = ProductionService.GetProductType(AreaId).Id;
            var productPropertys = ProductionService.GetProductPropertys(AreaId);
            return View(productPropertys);
        }

        [HttpGet]
        public ActionResult Edit(Guid? id)
        {
            SaveProductModel model;
            if (id == null)
            {
                #region 新增
                var productPropertys = ProductionService.GetProductPropertys(AreaId);
                var productType = ProductionService.GetProductType(AreaId);
                model = new SaveProductModel
                {
                    ProductTypeId = productType.Id,
                    Propertys = productPropertys
                };
                #endregion
            }
            else
            {
                #region 编辑
                var product = ProductionService.ProductDetail(id.Value);
                model = new SaveProductModel
                {
                    Id = product.Id,
                    ProductTypeId = product.ProductTypeId,
                    ProductMinimumCount = product.ProductMinimumCount,
                    Propertys = product.PropertyValues.ToList()
                };

                #endregion
            }
            return View(model);
        }

        #region Ajax

        [HttpPost]
        [ModelValidation]
        public ActionResult Save(SaveProductModel model)
        {
            ProductionService.SaveProduct(new ProductDto
            {
                Id = model.Id,
                ProductTypeId = model.ProductTypeId,
                AreaId = AreaId,
                ProductMinimumCount = model.ProductMinimumCount,
                Propertys = model.Propertys
            });
            return Success();
        }

        public ActionResult Delete(Guid id)
        {
            ProductionService.RemoveProduct(id);
            return Success();
        }

        public ActionResult GetPagedList(ProductCriteria criteria)
        {
            var list = ProductionService.GetProductInfoPagedList(criteria);
            return list.ToBootstrapTableModel();
        }

        #endregion
    }
}